import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class DispatchTest {

	private ActiveXComponent objWord;
	private Dispatch document;

	private Dispatch wordObject;

	public static void main(String[] args) {
		DispatchTest t1 = new DispatchTest();

		try {
			t1.open("d:\\123.docx");
			t1.close();
		} catch (Exception e) {
			t1.close();
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}

	public void open(String filename) {
		objWord = new ActiveXComponent("Word.Application");

		wordObject = objWord.getObject();

		Dispatch.put(wordObject, "Visible", new Variant(true));

		Dispatch documents = objWord.getProperty("Documents").toDispatch();

		document = Dispatch.call(documents, "Open", filename).toDispatch();

		Dispatch disSelect;
		disSelect = Dispatch.call(objWord, "Selection").toDispatch();
		Dispatch.call(disSelect, "TypeText", "123");
		Dispatch.call(disSelect, "TypeParagraph");
		// Dispatch.call(disSelect, "TypeText", "QQ:21807822″);
		Dispatch.call(disSelect, "TypeParagraph");
		Dispatch.call(disSelect, "TypeText", "e-mail:dukejoe@163.com");

		Dispatch disTables;
		disTables = Dispatch.call(document, "Tables").toDispatch();
		Dispatch disRange;
		disRange = Dispatch.call(disSelect, "Range").toDispatch();
		Dispatch.call(disTables, "Add", disRange, 3, 4, 1);

		Dispatch disTable;
		disTable = Dispatch.call(disTables, "Item", 1).toDispatch();
		Dispatch.put(disTable, "ApplyStyleColumnBands", 1);

		Dispatch.call(disSelect, "MoveDown", 5, 2, 2);
		Dispatch.call(disSelect, "MoveRight", 1, 3, 2);
		Dispatch disParagraphFormat;
		disParagraphFormat = Dispatch.get(disSelect, "ParagraphFormat")
				.toDispatch();
		Dispatch.put(disParagraphFormat, "Alignment", 1);

		Dispatch.call(disSelect, "MoveDown", 5, 1);
		Dispatch.call(disSelect, "TypeParagraph");
		Dispatch.call(disSelect, "TypeText", "345");
		Dispatch.call(disSelect, "TypeParagraph");
		Dispatch.call(disSelect, "TypeText", "678");
		Dispatch.call(disSelect, "TypeParagraph");
	}

	public void close() {
		Dispatch.call(document, "Close");
		Dispatch.call(wordObject, "quit");
	}
}